/*
 * This file is part of quickLoad, a software for gamers
 *
 * Copyright (C) 2005-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

namespace QuickLoad.UI
{
    public partial class FormUpdate : Form
    {
        AutoUpdater.AutoUpdateChecker m_upd;
        public FormUpdate(AutoUpdater.AutoUpdateChecker upd)
        {
            InitializeComponent();
            m_upd = upd;
            Control.CheckForIllegalCrossThreadCalls = false;
            m_upd.UpdateProgressChanged += new AutoUpdater.AutoUpdateChecker.UpdateProgressChangedEventHandler(m_upd_UpdateProgressChanged);
            upd.GetUpdateFileAsync(upd.UpdateFileURL,Path.GetTempPath() + Path.DirectorySeparatorChar + "quickLoad");
        }

        void m_upd_UpdateProgressChanged(object sender, AutoUpdater.UpdateEventArgs e)
        {
            progressBar1.Value = e.Progress;
            Text = lang.ResourceManager.GetString("Update" + e.Status.ToString()) + " (" + e.Progress.ToString() + "%)";
            if (e.Status == AutoUpdater.UpdateStatus.Complete)
            {
                //Text = "Download complete!";
                StartInstaller();
            }
            else if (e.Status == AutoUpdater.UpdateStatus.Downloading)
            {
                lStatus.Text = String.Format(lang.UpdateBytes,e.ErrorMessage);
            }
            else if(e.Status == AutoUpdater.UpdateStatus.Failed)
            {
                lStatus.Text = lang.UpdateFailed + ": " + e.ErrorMessage;
                MessageBox.Show(e.ErrorMessage,lang.UpdateFailed);
            }
        }
        void StartInstaller()
        {
            bool failed = false;
            ZipInputStream s = null;
            FileStream fs = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(m_upd.DownloadedFile));
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != "AutoUpdateInstaller.exe" && theEntry.Name != "ICSharpCode.SharpZipLib.dll")
                        continue;
                    FileInfo fi =
                        new FileInfo(Path.GetDirectoryName(m_upd.DownloadedFile) + Path.DirectorySeparatorChar +
                                     theEntry.Name.Replace("/", Path.DirectorySeparatorChar.ToString()));
                    
                    fs = new FileStream(fi.FullName, FileMode.Create, FileAccess.Write);
                    int zipbytes;
                    const int BLOCK_SIZE = 2048;
                    Byte[] zipbuffer = new Byte[BLOCK_SIZE];
                    while ((zipbytes = s.Read(zipbuffer, 0, zipbuffer.Length)) > 0)
                    {
                        fs.Write(zipbuffer, 0, zipbytes);
                        Application.DoEvents();
                    }
                    fs.Close();
                }
                //MessageBox.Show("Update successful!");
                System.Diagnostics.Process.Start(
                    Path.GetDirectoryName(m_upd.DownloadedFile) + Path.DirectorySeparatorChar +
                    "AutoUpdateInstaller.exe",
                    "\"" + m_upd.DownloadedFile + "\" \"" + Path.GetDirectoryName(Application.ExecutablePath) + "\"");
            }
            catch (Exception ex)
            {
                failed = true;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (s != null)
                    s.Close();
                if (fs != null)
                    fs.Close();
                if(!failed)
                    Application.Exit();
            }
        }
    }
}